<template>
  <div class="chat-sidebar">
    <!-- 顶部操作区 -->
    <div class="sidebar-header">
      <el-button
        type="primary"
        :icon="Plus"
        @click="handleCreateSession"
        class="new-chat-btn"
        size="default"
      >
        新对话
      </el-button>

      <el-tooltip content="折叠侧边栏" placement="bottom">
        <el-button
          :icon="Fold"
          @click="$emit('toggle-sidebar')"
          text
          size="default"
          class="collapse-sidebar-btn"
        />
      </el-tooltip>
    </div>

    <!-- 会话列表 -->
    <div class="sessions-container">
      <div class="sessions-header" @click="toggleSessionsCollapse">
        <div class="sessions-header-content">
          <span class="sessions-title">历史对话</span>
          <span class="sessions-count">({{ sessions?.length || 0 }})</span>
        </div>
        <el-icon class="collapse-icon" :class="{ collapsed: sessionsCollapsed }">
          <ArrowDown />
        </el-icon>
      </div>

      <el-collapse-transition>
        <div v-show="!sessionsCollapsed" class="sessions-list">
          <div
            v-for="session in sessions"
            :key="session.id"
            class="session-item"
            :class="{ active: currentSession?.id === session.id }"
            @click="handleSessionClick(session)"
          >
          <div class="session-content">
            <div class="session-title" :title="session.title">
              {{ session.title }}
            </div>
            <div class="session-meta">
              <span class="message-count">{{ session.messageCount }} 条消息</span>
              <span class="last-time">{{ formatTime(session.updatedAt) }}</span>
            </div>
            <div v-if="session.lastMessage" class="session-preview">
              {{ session.lastMessage }}
            </div>
          </div>
          
          <div class="session-actions" @click.stop>
            <el-dropdown trigger="click" @command="(command) => handleSessionAction(command, session)">
              <el-button text :icon="MoreFilled" size="small" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="rename" :icon="Edit">重命名</el-dropdown-item>
                  <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
          <!-- 空状态 -->
          <div v-if="!sessions || sessions.length === 0" class="empty-state">
            <el-icon class="empty-icon"><ChatDotRound /></el-icon>
            <p class="empty-text">还没有对话记录</p>
            <p class="empty-hint">点击上方"新对话"按钮开始第一次聊天</p>
          </div>
        </div>
      </el-collapse-transition>
    </div>

    <!-- 重命名对话框 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名对话"
      width="400px"
      :before-close="handleRenameCancel"
    >
      <el-form @submit.prevent="handleRenameConfirm">
        <el-form-item label="对话标题">
          <el-input
            v-model="newTitle"
            placeholder="请输入新的对话标题"
            maxlength="200"
            show-word-limit
            ref="titleInputRef"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleRenameCancel">取消</el-button>
        <el-button type="primary" @click="handleRenameConfirm" :loading="renaming">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, MoreFilled, Edit, Delete, ChatDotRound, ArrowDown, Fold } from '@element-plus/icons-vue'
import { useAIChatStore } from '@/stores/aiChatStore'
import type { ChatSession } from '@/types/aiChat'

const aiChatStore = useAIChatStore()

// 计算属性
const sessions = computed(() => aiChatStore.sessions)
const currentSession = computed(() => aiChatStore.currentSession)

// 折叠状态
const sessionsCollapsed = ref(false)

// 重命名相关状态
const renameDialogVisible = ref(false)
const newTitle = ref('')
const renamingSession = ref<ChatSession | null>(null)
const renaming = ref(false)
const titleInputRef = ref()

/**
 * 切换会话列表折叠状态
 */
const toggleSessionsCollapse = () => {
  sessionsCollapsed.value = !sessionsCollapsed.value
}

/**
 * 创建新会话
 */
const handleCreateSession = async () => {
  try {
    await aiChatStore.createNewSession()
  } catch (error) {
    console.error('Create session failed:', error)
  }
}

/**
 * 点击会话项
 */
const handleSessionClick = async (session: ChatSession) => {
  if (currentSession.value?.id === session.id) return
  
  try {
    await aiChatStore.switchToSession(session.id)
  } catch (error) {
    console.error('Switch session failed:', error)
  }
}

/**
 * 会话操作处理
 */
const handleSessionAction = async (command: string, session: ChatSession) => {
  switch (command) {
    case 'rename':
      handleRenameStart(session)
      break
    case 'delete':
      handleDeleteSession(session)
      break
  }
}

/**
 * 开始重命名
 */
const handleRenameStart = (session: ChatSession) => {
  renamingSession.value = session
  newTitle.value = session.title
  renameDialogVisible.value = true
  
  nextTick(() => {
    titleInputRef.value?.focus()
  })
}

/**
 * 确认重命名
 */
const handleRenameConfirm = async () => {
  if (!renamingSession.value || !newTitle.value.trim()) {
    ElMessage.warning('请输入对话标题')
    return
  }
  
  try {
    renaming.value = true
    await aiChatStore.updateSessionTitle(renamingSession.value.id, newTitle.value.trim())
    renameDialogVisible.value = false
  } catch (error) {
    console.error('Rename session failed:', error)
  } finally {
    renaming.value = false
  }
}

/**
 * 取消重命名
 */
const handleRenameCancel = () => {
  renameDialogVisible.value = false
  renamingSession.value = null
  newTitle.value = ''
}

/**
 * 删除会话
 */
const handleDeleteSession = async (session: ChatSession) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除对话"${session.title}"吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    await aiChatStore.deleteSessionById(session.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete session failed:', error)
    }
  }
}

/**
 * 格式化时间
 */
const formatTime = (timeStr: string) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - time.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return time.toLocaleDateString()
}
</script>

<style scoped>
.chat-sidebar {
  width: 230px;
  height: 100%;
  background: var(--el-bg-color-page);
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  gap: 8px;
}

.new-chat-btn {
  flex: 1;
  height: 40px;
  font-weight: 500;
}

.collapse-sidebar-btn {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  flex-shrink: 0;
}

.sessions-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.sessions-header {
  padding: 16px 16px 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: background-color 0.2s;
  border-radius: 6px;
  margin: 0 8px;

  &:hover {
    background: var(--el-fill-color-light);
  }

  .sessions-header-content {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .collapse-icon {
    font-size: 16px;
    color: var(--el-text-color-secondary);
    transition: transform 0.3s ease;

    &.collapsed {
      transform: rotate(-90deg);
    }
  }
}

.sessions-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.sessions-count {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.sessions-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px 16px;
}

.session-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 8px;
  margin-bottom: 4px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.session-item:hover {
  background: var(--el-fill-color-light);
}

.session-item.active {
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
}

.session-content {
  flex: 1;
  min-width: 0;
}

.session-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.message-count,
.last-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.session-preview {
  font-size: 12px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.session-item:hover .session-actions {
  opacity: 1;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--el-text-color-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: var(--el-text-color-placeholder);
}

.empty-text {
  font-size: 14px;
  margin-bottom: 8px;
  color: var(--el-text-color-regular);
}

.empty-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 滚动条样式 */
.sessions-list::-webkit-scrollbar {
  width: 4px;
}

.sessions-list::-webkit-scrollbar-track {
  background: transparent;
}

.sessions-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 2px;
}

.sessions-list::-webkit-scrollbar-thumb:hover {
  background: #a8abb2;
}
</style>
